import 'dart:async';

import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/utils/str_util.dart';
import 'package:kq_flutter_tv_widgets/resources/kq_theme_colors.dart';

/// 时钟控件，实时刷新系统时间
class KqSystemTime extends StatefulWidget {
  /// 时间格式化，默认格式"2018-01-08 12:31"
  final String Function()? timeFormatter;

  /// 字体大小，默认18
  final double? fontSize;

  /// 文字颜色，默认白色
  final Color? textColor;

  const KqSystemTime(
      {Key? key, this.fontSize, this.textColor, this.timeFormatter})
      : super(key: key);

  @override
  KqSystemTimeState createState() => KqSystemTimeState();
}

class KqSystemTimeState extends State<KqSystemTime> {
  Timer? _timer;
  String time = '';

  @override
  void initState() {
    super.initState();
    Timer.periodic(const Duration(seconds: 1), (timer) {
      _timer = timer;
      setState(() {
        time = widget.timeFormatter == null
            ? StrUtil.formatDatetimeYMDHm(DateTime.now(), split: '-')
            : widget.timeFormatter!();
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Text(
      time,
      style: TextStyle(
        fontSize: widget.fontSize ?? 18.sp,
        color: widget.textColor ?? KqThemeColors.textWhite,
      ),
    );
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }
}
